<template>
  <!-- 收银台 - 支付方式 -->
  <view class="pay-container">
    <view class="boxS price-box">
      <view class="headerss">金额合计</view>
      <view class="price-num">
        ￥
        <text style="color: #333333; font-size: 54rpx">{{ price }}</text>
        元
      </view>
    </view>
    <view class="payDate boxS">
      <view class="p-head">选择支付方式</view>
      <view class="pay-mind">
        <radio-group @change="radioChange">
          <label v-for="item in payTypes" :key="item.name">
            <view class="radio-item">
              <view class="left">
                <i-icon
                  :icon="item.icon"
                  class="middle mr-10"
                  type="single"
                  :size="item.value === 1 ? '56rpx' : '60rpx'"
                  :color="item.color"
                ></i-icon>
                {{ item.name }}
              </view>
              <view class="right"
                ><radio
                  :value="item.value"
                  color="#FBD220"
                  :checked="item.value === 0"
              /></view>
            </view>
          </label>
        </radio-group>
        <button class="goPay" @click="$u.debounce(submit, 1000)">确认支付</button>
      </view>
    </view>
    <view class="bottoms">
      <text>如有疑问请联系客服：</text>
      <text style="color: #fbb000" @click="call('4000909987')">4000909987</text>
    </view>
    <u-modal
      v-model="mShow6"
      title="温馨提示"
      content="订单系统收款略有延迟，支付成功后可刷新订单查看结果"
      cancel-text="支付失败"
      confirm-text="支付成功"
      confirm-color="#EB5C02"
      :show-cancel-button="true"
      @confirm="confirmHE"
      @cancel="mShow6 = false"
    ></u-modal>
    <!-- 确认弹框 -->
    <u-popup
      v-model="mShowye"
      mode="center"
      border-radius="14"
      width="540rpx"
      height="358rpx"
    >
      <view class="popup-title">温馨提示</view>
      <view class="popup-content">请你确认是否支付？</view>
      <view class="btnWrap flex">
        <view class="width-50 left" @click="mShowye = false"
          ><view class="inline-block">取消支付</view></view
        >

        <view class="width-50 right" @click="$u.throttle(confirmYe, 1000)"
          >确认支付</view
        >
      </view>
    </u-popup>
    <!-- 输入支付密码 -->
    <u-popup
      v-model="yepsdStatus"
      mode="center"
      border-radius="14"
      width="540rpx"
      height="388rpx"
    >
      <view class="popup-title">请输入支付密码</view>
      <view class="popup-content"
        ><u-message-input
          :focus="true"
          :dot-fill="true"
          mode="bottomLine"
          width="60"
          active-color="ffbb00"
          @finish="finish"
          :maxlength="6"
        ></u-message-input
      ></view>
      <view class="btnWrap flex">
        <view class="width-50 left" @click="yepsdStatus = false"
          ><view class="inline-block">取消支付</view></view
        >

        <view
          class="width-50 right"
          @click="$u.throttle(ClientBalancePay, 1000)"
          >确认支付</view
        >
      </view>
    </u-popup>
    <!-- <u-modal v-model="mShowye" cancel-text="取消支付" title="温馨提示" content='请你确认是否支付'  confirm-text="确认支付" @confirm="confirmYe" ref="uModal" :async-close="true" :show-cancel-button="true" ></u-modal> -->
    <!-- 支付宝提交表单位置 -->
    <!-- #ifdef H5 -->
    <view class="pay-submit" v-html="formDom"></view>
    <!-- #endif -->
  </view>
</template>

<script>
import Pay from '@/utils/pay.js' // 支付对象

export default {
  data() {
    return {
      price: 888,
      type: 'accessory', //  入口标识，carGoods: 车品，accessory: 配件,security：保证金 ，newcar:新车，
      orderNo: '058794d829f64ec5a24ea1ab99d34d7f', //  订单号id
      // 支付方式列表
      payTypes: [
        {
          name: '支付宝支付',
          value: 0,
          icon: 'iconzhifubao',
          color: '#02A9F1',
        },
        {
          name: '微信支付',
          value: 1,
          icon: 'iconweixinzhifu',
          color: '#09BB07',
        },
        {
          name: '余额支付',
          value: 2,
          icon: 'iconyuezhifu',
          color: '#FBB000',
        },
      ],
      payPlatformType: 0, // 支付平台值

      // 支付环境
      // #ifdef H5
      payPlatformDetailType: 1,
      // #endif

      // #ifdef APP-PLUS
      payPlatformDetailType: 3,
      // #endif

      formDom: '', // 表单标签元素

      mShow6: false,
      mShowye: false,

      isOrderlist: 0, // 1为从订单列表或订单详情进入页面

      isSetPayPsd: false,
      yepsdStatus: false, //余额支付
      payPassword: '', //密码
    }
  },

  onLoad(e) {
    console.log(e)
    this.orderNo = e.orderNo
    this.price = e.price
    this.type = e.type
    this.isOrderlist = parseInt(e.isOrderlist)
    console.log('token', uni.getStorageSync('token'))
    this.IsExistPayPwd()
  },

  onBackPress() {
    if (this.isOrderlist === 1) {
      return false
    } else {
      uni.redirectTo({
        url: `/pages_order/carGoodsOrder/orderManage/orderManage?index=1`,
      })
      return true
    }
  },

  methods: {
    async IsExistPayPwd() {
      try {
        const res = await this.$api.user.IsExistPayPwd()
        console.log(res)
        this.isSetPayPsd = res.data
      } catch (e) {
        console.log(e)
        //TODO handle the exception
      }
    },
    // 单选监听
    radioChange(e) {
      this.payPlatformType = e.target.value
      console.log(e.target.value)
    },

    // 跳转到成功页面
    goSuccessPage() {
      uni.redirectTo({
        url: `/pages_order/paySuccess/paySuccess?id=${this.orderNo}&type=${this.type}`,
      })
    },

    // app端支付方法
    async payApp(orderInfo) {
      switch (this.payPlatformType) {
        // 支付宝
        case 0:
          try {
            // let data =
            //   'app_id=2021001164691321&biz_content=%7B%22body%22%3A%22%E8%B4%AF%E9%80%9A%E8%BD%B4......%22%2C%22out_trade_no%22%3A%22O13347425518355783%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E9%85%8D%E4%BB%B6%E6%94%AF%E4%BB%98%22%2C%22total_amount%22%3A%220.05%22%7D&charset=utf-8&format=json&method=alipay.trade.app.pay&notify_url=https%3A%2F%2Ftestapi.yzsheng.com%2Fapi%2Fbusiness%2Fcore%2FAlipayNotify%2FAPPPartsOrderPayNotify%2FOrderPayNotify&sign_type=RSA2&timestamp=2020-12-04+15%3A34%3A43&version=1.0&sign=fAigUF9P09TvUQAIghjy4quGJ9iNPv1BKNOerXLoiZR0e%2F1h3JwAtOGEuTPDtAyZ2NvnVyQJIVb2fQaUQ5Bvgiw4fcP0zMscZUjzrAwAwSqUHYQIn3lXKSJde9PlUG0zlAvtM7W1OrgEnkL4xaQeY7%2FdTRyD9FSvgSpQpHjEd7bdlud9MJvAtzmNH6A3NoXmIhFIxw6zdwsWwccFxDEmDAGmd0H34nONLJfz%2BpZqyEHn431BiM8mtaF2Yeiigp%2Bgxvbf1BdkuCGJ%2FsVSdzMxXfLq1SDo%2FUXtDCat2eJa3qjB6dS%2F0dw36sdFiYvftx9HUb1fQB8MkYUHKFPXuhxDtg%3D%3D' ||
            //   orderInfo
            const res = await Pay.alipay(orderInfo)
            console.log('app支付宝支付', res)
            this.goSuccessPage()
            uni.showModal({
              content: '确认是否已支付成功？',
              confirmColor: '#FBB000',
              success: (res) => {
                if (res.confirm) {
                  this.goSuccessPage()
                } else if (res.cancel) {
                  this.goSuccessPage()
                }
              },
            })
          } catch (err) {
            let tips = `支付失败`
            uni.showToast({ title: tips, icon: 'none' })
            console.log('app支付宝支付失败', err)
            if (err.errMsg.includes('canceled')) {
              uni.showToast({
                title: '已取消支付',
                icon: 'none',
              })
            }
            uni.showModal({
              content: '确认是否已支付成功？',
              confirmColor: '#FBB000',
              success: (res) => {
                if (res.confirm) {
                  console.log(err)
                } else if (res.cancel) {
                  console.log(err)
                }
              },
            })
          }
          break

        // 微信
        case 1:
          try {
            let infoObj = JSON.parse(orderInfo.parameter)
            let data = {
              appid: infoObj.appid,
              noncestr: infoObj.noncestr,
              package: infoObj.package,
              partnerid: infoObj.partnerid,
              prepayid: infoObj.prepayid,
              sign: infoObj.sign,
              timestamp: infoObj.timestamp,
            }
            console.log(infoObj, data)
            const res = await Pay.wxpay(data)
            console.log('app微信支付', res)
            uni.showModal({
              content: '确认是否已支付成功？',
              confirmColor: '#FBB000',
              success: (res) => {
                if (res.confirm) {
                  this.goSuccessPage()
                } else if (res.cancel) {
                  this.goSuccessPage()
                }
              },
            })
          } catch (err) {
            let tips = `支付失败`
            uni.showToast({ title: tips, icon: 'none' })
            console.log('app微信支付失败', err)
            if (err.errMsg.includes('canceled')) {
              uni.showToast({
                title: '已取消支付',
                icon: 'none',
              })
            } else {
              uni.showModal({
                content: '确认是否已支付成功？',
                confirmColor: '#FBB000',
                success: (res) => {
                  if (res.confirm) {
                    console.log(err)
                  } else if (res.cancel) {
                    console.log(err)
                  }
                },
              })
            }
          }
          break
      }
    },

    // H5端支付方法
    payH5(data) {
      switch (this.payPlatformType) {
        // 支付宝
        case 0:
          this.formDom = data
          this.$nextTick(() => {
            document.forms['submit'].submit()
          })
          break

        // 微信
        case 1:
          let a = document.createElement('a')
          a.href = data.mwebUrl
          a.target = '_blank'
          a.click()
          console.log(a)
          window.location.href = data.mwebUrl
          break
      }
    },

    // 车品调用支付方法
    async carGoodsPay() {
      let data = {
        orderId: this.orderNo,
        payModule: 0,
        payPlatform: {
          payPlatformType: this.payPlatformType, // 支付平台
          payPlatformDetailType: this.payPlatformDetailType, // 支付环境，H5端还是APP端等
        },
        // #ifdef H5
        returnUrl: encodeURI(
          window.location.origin +
            window.location.pathname +
            `#/pages_order/paySuccess/paySuccess?id=${this.orderNo}&type=${this.type}`
        ),
        // #endif
      }
      console.log('车品支付请求参数', data)
      try {
        const res = await this.$api.pay.OrderCarSuppliesPay(data)
        console.log('车品支付接口成功', res)
        // #ifdef APP-PLUS
        this.payApp(res.data.data)
        // #endif

        // #ifdef H5
        this.payH5(res.data.data)
        // #endif
      } catch (err) {
        console.log('车品支付接口错误', err)
      }
    },

    // 寻配件调用支付方法
    async accessoryPay() {
      let data = {
        id: this.orderNo,
        payModule: 1,
        payPlatform: {
          payPlatformType: this.payPlatformType, // 支付平台
          payPlatformDetailType: this.payPlatformDetailType, // 支付环境，H5端还是APP端等
        },
        // #ifdef H5
        returnUrl: encodeURI(
          window.location.origin +
            window.location.pathname +
            `#/pages_order/paySuccess/paySuccess?id=${this.orderNo}&type=${this.type}`
        ),
        // #endif
      }
      console.log('请求参数', data)
      try {
        const res = await this.$api.pay.PartsPay(data)
        console.log('寻配件支付接口成功', res)
        // #ifdef APP-PLUS
        this.payApp(res.data.data)
        // #endif

        // #ifdef H5
        console.log(res.data)
        this.payH5(res.data.data)
        // #endif
      } catch (err) {
        console.log('寻配件支付接口错误', err)
      }
    },

    // 点击确认支付
    // 通过判断type为车品还是配件，调用对应的支付方法
    submit() {
      if (this.payPlatformType === 2) {
        if (this.isSetPayPsd) {
          this.yepsdStatus = true
        } else {
          uni.showToast({
            title: '请先设置支付密码',
            icon: 'none',
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages_common/pages_me/assets/setPassword/setPsd',
            })
          }, 1200)
        }
      } else {
        if (this.type === 'accessory') {
          this.accessoryPay()
        } else {
          this.carGoodsPay()
        }
      }
    },
    async ClientBalancePay() {
      if (this.payPassword.length === 6) {
        let data = {
          id: this.orderNo,
          userInputPayPassword: this.payPassword,
          payModule: this.type === 'accessory' ? 1 : 0, //购车--2 维保--3 福利购--4
        }
        try {
          const res = await this.$api.common.BusBalancePay(data)
          console.log('余额支付', res)
          uni.showToast({
            title: '支付成功！',
            icon: 'success',
          })
          this.paypsd = false
          setTimeout(() => {
            uni.navigateBack(2)
          }, 1200)
        } catch (err) {
          console.log('支付失败', err)
        }
      } else {
        uni.showToast({
          title: '请输入正确的支付密码',
          icon: 'none',
        })
      }
    },
    finish(e) {
      console.log(e)
      this.payPassword = e
    },
    // 打电话
    call(phone) {
      AddMobileContactData(this.$store.state.userInfoDetail.store.storeId)
      uni.makePhoneCall({
        phoneNumber: phone, //仅为示例
      })
    },

    confirmHE() {},
    confirm() {},
  },
}
</script>

<style lang="scss" scoped>
.pay-container {
  width: 100%;
  min-height: 100vh;
  padding-top: 12rpx;
  background-color: #f6f6f6;

  .boxS {
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.14);
    border-radius: 10rpx;
    padding: 0 20rpx;
    width: 702rpx;
    margin: 0 auto;
  }

  // 金额合计
  .price-box {
    height: 160rpx;
    margin-top: 23rpx;

    .headerss {
      font-size: 30rpx;
      font-weight: 500;
      color: rgba(102, 102, 102, 1);
      padding-top: 28rpx;
    }
    // 金额数
    .price-num {
      text-align: center;
    }
  }
  .mids {
    height: 300rpx;
    margin-top: 12rpx;

    .m-head {
      font-size: 30rpx;
      height: 87rpx;
      line-height: 87rpx;
      font-weight: 500;
      color: rgba(102, 102, 102, 1);
      margin-bottom: 20rpx;
    }
  }
  .payDate {
    margin-top: 23rpx;
    padding-bottom: 20rpx;

    .p-head {
      height: 96rpx;
      line-height: 96rpx;
      border-bottom: 2rpx solid #eeeeee;
      font-size: 30rpx;
      font-weight: 500;
      color: rgba(102, 102, 102, 1);
    }

    .goPay {
      width: 662rpx;
      height: 88rpx;
      background: linear-gradient(-90deg, #fbd220, #ffe23e);
      border-radius: 44rpx;
      text-align: center;
      line-height: 88rpx;
      font-size: 32rpx;
      color: #333;
      margin-top: 40rpx;
    }

    .goPay:after {
      border: 0rpx;
    }

    // 单选支付方式
    .pay-mind {
      margin-top: 20rpx;

      // 单选项
      .radio-item {
        line-height: 60rpx;
        padding: 15rpx 0px;
        font-size: 30rpx;
        color: #666;
        display: flex;

        .right {
          margin-left: auto;
        }
      }
    }
  }

  .bottoms {
    width: 702rpx;
    margin: 0 auto;
    font-size: 26rpx;
    font-weight: 500;
    color: rgba(153, 153, 153, 1);
    margin-top: 40rpx;
  }
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  padding-top: 58rpx;
  text-align: center;
  color: #333;
}
.popup-content {
  text-align: center;
  font-size: 30rpx;
  font-weight: 500;
  color: #666666;
  padding-top: 38rpx;
}

// 弹框样式
.btnWrap {
  width: 80%;
  margin: 38rpx auto;
  // border-radius: 20rpx;
  text-align: center;
  height: 88rpx;

  .left {
    color: #ffe03b;
    line-height: 88rpx;
    background-color: #333333;
    border-radius: 40rpx 0px 0rpx 40rpx;
    border-right: 1rpx solid #fff;
  }

  .right {
    color: #333333;
    line-height: 88rpx;
    background-color: #ffe03b;
    border-left: 1rpx solid #fff;
    border-radius: 0px 40rpx 40rpx 0rpx;
  }
}
</style>
